<?php

declare(strict_types=1);

namespace app\util;

use app\service\sys\ConfigService;
use InvalidArgumentException;

class QiniuUtil
{
    public static function getUploadToken(ConfigService $configService): array
    {
        $config = $configService->get('qiniu', []);
        if (is_string($config)) {
            $config = json_decode($config, true) ?: [];
        }

        $accessKey = $config['accessKey'] ?? $config['access_key'] ?? '';
        $secretKey = $config['secretKey'] ?? $config['secret_key'] ?? '';
        $bucket = $config['bucket'] ?? '';
        $domain = $config['domain'] ?? '';
        $uploadUrl = $config['uploadUrl'] ?? $config['upload_url'] ?? 'http://upload.qiniup.com';

        if ($accessKey === '' || $secretKey === '' || $bucket === '' || $domain === '') {
            throw new InvalidArgumentException('七牛云存储配置不完整，请联系管理员');
        }

        $prefix = date('Ym');

        $auth = new \Qiniu\Auth($accessKey, $secretKey);
        $policy = [
            'saveKey' => trim($prefix, '/') . '/$(etag)$(ext)',
        ];

        $token = $auth->uploadToken($bucket, null, 3600, $policy);

        return [
            'domain' => rtrim($domain, '/'),
            'uploadToken' => $token,
            'uploadUrl' => $uploadUrl,
        ];
    }
}
